package com.qf.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author WzYu
 * @date 2022-7-12 下午 5:27
 * ReentrantLock锁  测试
 *
 * 这体现在多线程情况下，锁能做到让线程之间有序运行，
 *
 * 如果没有锁，情况可能是 12,13,13,10,10,10,12，没有锁其他线程可能插队执行System.out.print
 */
public class LockTest implements Runnable {

    public static ReentrantLock lock = new ReentrantLock();//创建锁对象
    private int thold;

    public LockTest(int h) {
        this.thold = h;
    }

    /**
     * 一共五个锁
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 10; i < 15; i++) {
            new Thread(new LockTest(i),"name-" + i).start();
        }
    }

    @Override
    public void run() {
        try {
            Thread.sleep(100);
            //lock.lock(); //获取锁
            System.out.println("lock threadName:" + Thread.currentThread().getName());
            {
                System.out.print(" writeStart ");
                //锁循环15次
                for (int i = 0; i < 15; i++) {


                    //为了体现锁的作用，这里sleep睡眠0.1秒，增加哪个线程获取锁的随机性
                    //因为线程唤醒后，会开始尝试获取锁，多个线程下竞争一把锁是随机的
                    Thread.sleep(100);
                    System.out.print(thold+",");
                }
                System.out.println(" writeEnd");
            }
            System.out.println("unlock threadName:" + Thread.currentThread().getName() + "\r\n");
            //lock.unlock(); //锁释放
        } catch (InterruptedException e) {
        }
    }
}